<?php

namespace app\admin\controller;

use app\admin\model\BydAgreement;
use app\admin\model\Bydletter;
use app\common\controller\Backend;
use app\common\controller\News;
use think\db;
/**
 * 销售员
 *
 * @icon fa fa-circle-o
 */
class BydUserSale extends Backend
{
    
    /**
     * BydUserSale模型对象
     * @var \app\admin\model\BydUserSale
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BydUserSale;
        $this->view->assign("stateList", $this->model->getStateList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['byduser'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $user=\app\admin\model\BydUser::find($params['user_id']);
                if($params['state']==1){
                      $useragfind=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->find();
                      if(!empty($useragfind)){
                          $agment=BydAgreement::where('id',$useragfind['agid'])->find();

           // $bbsreal=BydUserSale::where('user_id',$row['userid'])->find();
//            if(!empty($des)){
                $name=$row['name'].$row['idcart'];
//            }else{
//                $name='乙方';
//            }
                          $startime= date ( 'Y-m-d' );
                          $endtime=date ( 'Y-m-d' , strtotime ( '+364 day' ));
                          $arrs=$agment['content'];
                          $arrs=str_replace('{$name}',$name,$arrs);
                          $arrs=str_replace('{$star}',$startime,$arrs);
                          $arrs=str_replace('{$end}',$endtime,$arrs);
                          $content=$arrs;
                          $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->update(['status'=>1,'content'=>$content,'realname'=>$row['name'],'idcart'=>$row['idcart']]);

                      }



                    $myself= rand(1, 999);
                    $find=\app\admin\model\BydIdentity::where('id',$params['level'])->find();//查询身份分佣金额
                    $rand=rand(1,9999);
                    $head=$find['idenhead'];
                    $num="$head$rand";
                    $bh=\app\admin\model\BydDesigner::where('id',$row['id'])->update(['bh'=>$num]);
                    $arr=[
                        'idcar'=>$params['level'],
                        'user_id' =>$params['user_id'],
                    ];

                    $level=\app\api\model\BydIdentity::newxsub($arr);
                    $arr=[
                        'openid'=>$user['openid'],
                        'thing2'=>"您的美居会员申请已通过",//$data['news'],
                        'thing6'=>"请前往小程序查看",

                    ];
                    $new=new News();
                    $news=$new->vr($arr);
                }elseif($params['state']==2){
                    $yy=$row['bhly'];
                    $arr=[
                        'openid'=>$user['openid'],
                        'thing2'=>"您的美居会员申请被拒绝",//$data['news'],
                        'thing6'=>"请前往小程序查看",
                    ];
                    $new=new News();
                    $news=$new->vr($arr);

                    $add=new Bydletter();
                    $add->data([
                        'user_id'=>$params['user_id'],
                        'orderid'=>0,
                        'content'=>'您的美居会员申请被驳回',
                        'zt'=>$params['bhly'],
                        'state'=>0
                    ]);
                    $add->save();
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 检测是否有新退货消息
     */
    public function isHaveNewAfter()
    {
        $cache=\think\Cache::get('bbs');
        if(!empty($cache)){
            $tips = 'aftersale:tips:number';
            //edis = (new Redis())->getRedis();
            $tipsNumber = rand();
            $this->success('获取新销售员消息数量成功', null, $tipsNumber);
        }

    }

    /**
     * 已确认新退货消息
     */
    public function handleTui()
    {
        $type = $this->request->post('type');
        $tips = 'aftersale:tips:number';
        $tipsNumber = rand();
        \think\Cache::rm('bbs');
        $this->success('确认新销售员消息成功', null, $type);
    }
}
